package pers.lance.exam.dao.impl;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import pers.lance.exam.dao.ItemDao;
import pers.lance.exam.pojo.Base;
import pers.lance.exam.pojo.Item;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

/**
 * @ Author     ：LILA3
 * @ Date       ：Created in 1:59 PM 7/31/2018
 */
@Repository
public class ItemDaoImpl implements ItemDao {
    @PersistenceContext(name = "em")
    EntityManager entityManager;

    @Transactional
    public Item add(Item item) {
        entityManager.persist(item);
        return item;
    }

    @Transactional
    public Item delete(Item item) {
        Item deleteItem = entityManager.find(Item.class, item.getId());
        entityManager.remove(deleteItem);
        return item;
    }

    public List<Item> findAll() {
        String sql = "From Item";
        return entityManager.createQuery(sql).getResultList();
    }

    public Item findById(Item item) {
        return entityManager.find(Item.class, item.getId());
    }

    public List<Item> findByBase(Base base) {
        String sql = "from Item iv where iv.base.id=:bid";
        Query query = entityManager.createQuery(sql);
        query.setParameter("bid", base.getId());
        return query.getResultList();
    }
}
